package com.sls.mall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.sls.common.to.es.SkuEsModel;
import com.sls.common.utils.R;
import com.sls.mall.search.constant.EsConstant;
import com.sls.mall.search.feign.ProductFeignService;
import com.sls.mall.search.service.MallSearchService;
import com.sls.mall.search.vo.AttrResponseVo;
import com.sls.mall.search.vo.SearchParam;
import com.sls.mall.search.vo.SearchResult;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.NestedQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class MallSearchServiceImpl implements MallSearchService {

    @Autowired
    private RestHighLevelClient client;
    @Autowired
    private ProductFeignService productFeignService;

    @Override
    public SearchResult search(SearchParam param) {
        SearchResult result = null;
        try {
            //1.构建查询条件
            SearchRequest searchRequest = buildSearchRequest(param);
            //2.执行检索请求
            SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
            //3.分析响应结果，封装数据
            result = buildSearchResponse(response, param);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 构建查询条件
     * @param param
     * @return
     */
    private SearchRequest buildSearchRequest(SearchParam param) {
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        /************1.构建bool -query*****************************/
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        //1.1 must 模糊匹配
        if(!StringUtils.isEmpty(param.getKeyword())){
            boolQuery.must(QueryBuilders.matchQuery("skuTitle",param.getKeyword()));
        }
        //1.2 bool filter 按三级分类id搜索
        if(!StringUtils.isEmpty(param.getCatalog3Id())){
            boolQuery.filter(QueryBuilders.termQuery("catalogId", param.getCatalog3Id()));
        }
        //1.3 bool filter 按品牌id集合查询
        if(param.getBrandId() != null && param.getBrandId().size() > 0){
            boolQuery.filter(QueryBuilders.termsQuery("brandId", param.getBrandId()));
        }
        //1.4 bool filter 有货无货查询
        if(param.getHasStock() != null){
            boolQuery.filter(QueryBuilders.termsQuery("hasStock", param.getHasStock()==1));
        }

        //1.5 按价格区间查询
        if(!StringUtils.isEmpty(param.getSkuPrice())){
            String[] s = param.getSkuPrice().split("_");
            RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("skuPrice");
            if(s.length == 2){
                boolQuery.filter(rangeQuery.gte(s[0]).lte(s[1]));
            } else if(s[0].startsWith("_")){
                boolQuery.filter(rangeQuery.lte(s[0]));
            } else if(s[0].endsWith("_")){
                boolQuery.filter(rangeQuery.gte(s[0]));
            }
        }

        //1.6 按属性查询
        if(param.getAttrs() != null && param.getAttrs().size() > 0){
            for (String attrStr : param.getAttrs()) {
                BoolQueryBuilder nestedBoolQuery = QueryBuilders.boolQuery();
                String[] attr = attrStr.split("_");
                String attrId = attr[0];
                String[] attrValues = attr[1].split(":");
                nestedBoolQuery.must(QueryBuilders.termQuery("attrs.attrId", attrId));
                nestedBoolQuery.must(QueryBuilders.termsQuery("attrs.attrValue", attrValues));
                NestedQueryBuilder nestedQueryBuilder = QueryBuilders.nestedQuery("attrs", nestedBoolQuery, ScoreMode.None);
                boolQuery.filter(nestedQueryBuilder);
            }
        }
        //把上面所有条件封装
        sourceBuilder.query(boolQuery);

        /************2.排序 分页*****************************/
        //2.1 排序
        if(!StringUtils.isEmpty(param.getSort())){
            String[] s = param.getSort().split("_");
            SortOrder order = s[1].equalsIgnoreCase("asc") ? SortOrder.ASC : SortOrder.DESC;
            sourceBuilder.sort(s[0], order);

        }
        //2.2 分页
        sourceBuilder.from((param.getPageNum()-1)*EsConstant.PRODUCT_PAGESIZE);
        sourceBuilder.size(EsConstant.PRODUCT_PAGESIZE);
        //2.3 高亮
        if(!StringUtils.isEmpty(param.getKeyword())){
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            highlightBuilder.field("skuTitle");
            highlightBuilder.preTags("<b style='color:red'>").postTags("</b>");
            sourceBuilder.highlighter(highlightBuilder);
        }

        /************3.聚合分析 *****************************/
        //3.1 品牌聚合
        TermsAggregationBuilder brand_agg = AggregationBuilders.terms("brand_agg");
        brand_agg.field("brandId").size(50);
        //品牌子聚合
        brand_agg.subAggregation(AggregationBuilders.terms("brand_name_agg").field("brandName").size(1));
        brand_agg.subAggregation(AggregationBuilders.terms("brand_img_agg").field("brandImg").size(1));
        sourceBuilder.aggregation(brand_agg);
        //3.2 分类聚合
        TermsAggregationBuilder catalogAgg = AggregationBuilders.terms("catalog_agg").field("catalogId").size(20);
        catalogAgg.subAggregation(AggregationBuilders.terms("catalog_name_agg").field("catalogName").size(1));
        sourceBuilder.aggregation(catalogAgg);

        //3.3 属性聚合
        NestedAggregationBuilder attrAgg = AggregationBuilders.nested("attr_agg", "attrs");
        // 属性子聚合
        TermsAggregationBuilder attrIdAgg = AggregationBuilders.terms("attr_id_agg").field("attrs.attrId");
        attrIdAgg.subAggregation(AggregationBuilders.terms("attr_name_agg").field("attrs.attrName").size(1));
        attrIdAgg.subAggregation(AggregationBuilders.terms("attr_value_agg").field("attrs.attrValue").size(50));
        attrAgg.subAggregation(attrIdAgg);
        sourceBuilder.aggregation(attrAgg);

        System.out.println("构建的DSL语句："+sourceBuilder.toString());
        SearchRequest searchRequest = new SearchRequest(new String[]{EsConstant.PRODUCT_INDEX}, sourceBuilder);
        return searchRequest;
    }

    /**
     * 封装返回数据
     * @param response
     * @return
     */
    private SearchResult buildSearchResponse(SearchResponse response, SearchParam param) {
        SearchResult result = new SearchResult();
        SearchHits hits = response.getHits();
        //1.封装返回的产品信息
        if(hits.getHits() != null && hits.getHits().length > 0){
            List<SkuEsModel> skuEsModels = new ArrayList<>();
            for (SearchHit hit : hits.getHits()) {
                String sourceAsString = hit.getSourceAsString();
                SkuEsModel sku = new SkuEsModel();
                SkuEsModel skuEsModel = JSON.parseObject(sourceAsString, SkuEsModel.class);
                //获取高亮部分
                if(!StringUtils.isEmpty(param.getKeyword())){
                    HighlightField skuTitle = hit.getHighlightFields().get("skuTitle");
                    String s = skuTitle.getFragments()[0].toString();
                    skuEsModel.setSkuTitle(s);
                }
                skuEsModels.add(skuEsModel);
            }
            result.setProducts(skuEsModels);
        }

        //2.封装返回的分类信息
        ParsedLongTerms catalog_agg = response.getAggregations().get("catalog_agg");
        if(catalog_agg != null){
            List<SearchResult.CatalogVo> catalogVos = new ArrayList<>();
            List<? extends Terms.Bucket> buckets = catalog_agg.getBuckets();
            for (Terms.Bucket bucket : buckets) {
                SearchResult.CatalogVo vo = new SearchResult.CatalogVo();
                String keyAsString = bucket.getKeyAsString();
                vo.setCatalogId(Long.parseLong(keyAsString));
                //获取分类名称
                ParsedStringTerms catalog_name_agg = bucket.getAggregations().get("catalog_name_agg");
                String catalog_name = catalog_name_agg.getBuckets().get(0).getKeyAsString();
                vo.setCatalogName(catalog_name);
                catalogVos.add(vo);
            }
            result.setCatalogs(catalogVos);
        }

        //3.封装返回的品牌信息
        ParsedLongTerms brand_agg = response.getAggregations().get("brand_agg");
        if(brand_agg != null){
            List<SearchResult.BrandVo> brandVos = new ArrayList<>();
            List<? extends Terms.Bucket> buckets = brand_agg.getBuckets();
            for (Terms.Bucket bucket : buckets) {
                SearchResult.BrandVo brandVo = new SearchResult.BrandVo();
                String keyAsString = bucket.getKeyAsString();
                brandVo.setBrandId(Long.parseLong(keyAsString));
                //获取品牌名字
                String brand_name =((ParsedStringTerms)  bucket.getAggregations().get("brand_name_agg")).getBuckets().get(0).getKeyAsString();
                //获取品牌图片
                String brand_img = ((ParsedStringTerms) bucket.getAggregations().get("brand_img_agg")).getBuckets().get(0).getKeyAsString();

                brandVo.setBrandName(brand_name);
                brandVo.setBrandImg(brand_img);
                brandVos.add(brandVo);
            }
            result.setBrands(brandVos);
        }


        //4.封装返回的属性信息
        ParsedNested attr_agg = response.getAggregations().get("attr_agg");
        if(attr_agg != null){
            ParsedLongTerms attr_id_agg = attr_agg.getAggregations().get("attr_id_agg");
            List<SearchResult.AttrVo> attrVos = new ArrayList<>();
            List<? extends Terms.Bucket> buckets = attr_id_agg.getBuckets();
            for (Terms.Bucket bucket : buckets) {
                SearchResult.AttrVo attrVo = new SearchResult.AttrVo();
                long keyAsLong = bucket.getKeyAsNumber().longValue();
                attrVo.setAttrId(keyAsLong);

                String attr_name = ((ParsedStringTerms) bucket.getAggregations().get("attr_name_agg")).getBuckets().get(0).getKeyAsString();
                List<? extends Terms.Bucket> attr_value_agg = ((ParsedStringTerms) bucket.getAggregations().get("attr_value_agg")).getBuckets();
                List<String> collect = attr_value_agg.stream().map(item -> {
                    String keyValue = item.getKeyAsString();
                    return keyValue;
                }).collect(Collectors.toList());
                attrVo.setAttrName(attr_name);
                attrVo.setAttrValue(collect);

                attrVos.add(attrVo);
            }
            result.setAttrs(attrVos);
        }

        Long total = hits.getTotalHits().value;
        result.setTotal(total);
        int totalPages = (int) (total%EsConstant.PRODUCT_PAGESIZE == 0 ? total/EsConstant.PRODUCT_PAGESIZE : (total/EsConstant.PRODUCT_PAGESIZE+1));
        result.setTotalPages(totalPages);
        result.setPageNum(param.getPageNum());
        List<Integer> pageNavs = new ArrayList<>();
        for (int i = 1; i < totalPages; i++) {
            pageNavs.add(i);
        }
        result.setPageNavs(pageNavs);
        //构建面包屑导航数据
        if(param.getAttrs() != null && param.getAttrs().size() > 0){
            List<SearchResult.NavVo> collect = param.getAttrs().stream().map(attr -> {
                SearchResult.NavVo navVo = new SearchResult.NavVo();
                String[] s = attr.split("_");
                navVo.setNavValue(s[1]);
                R r = productFeignService.getAttrInfo(s[0]);
                if(r.getCode() == 0){
                    AttrResponseVo data = r.getData("attr", new TypeReference<AttrResponseVo>() {
                    });
                    navVo.setNavName(data.getAttrName());
                } else {
                    navVo.setNavName(s[0]);
                }
                //取消了这个面包屑后，移除当前条件
                String encode = null;
                try {
                    encode = URLEncoder.encode(attr, "UTF-8");
                    encode = encode.replace("+","%20");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                String queryString = param.get_queryString().replace("&attrs="+encode,"");
                navVo.setLink("http://search.slsmall.com/list.html?" + queryString);
                return navVo;
            }).collect(Collectors.toList());
            result.setNavs(collect);
        }

        return result;
    }
}
